package com.jiang.jixiang.ui.fragment;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.jiang.jixiang.R;
import com.jiang.jixiang.api.ApiUrl;
import com.jiang.jixiang.bean.NearbyNearbyMerchantBean;
import com.jiang.jixiang.bean.SellerInfoBean;
import com.jiang.jixiang.databinding.FragmentIndexBinding;
import com.jiang.jixiang.network.CommonalityModel;
import com.jiang.jixiang.network.NetWorkListener;
import com.jiang.jixiang.network.okHttpModel;
import com.jiang.jixiang.tools.PubDiaUtils;
import com.jiang.jixiang.ui.LoginActivity;
import com.jiang.jixiang.ui.MyOrderInfoActivity;
import com.jiang.jixiang.ui.NearbySellerActivity;
import com.jiang.jixiang.ui.NearbySellerInfoActivity;
import com.jiang.jixiang.ui.SearchActivity;
import com.ws.universal.tools.Constants;
import com.ws.universal.tools.base.BaseFragment;
import com.ws.universal.tools.countdown.CommitTimer;
import com.ws.universal.tools.eventbus.BaseBusData;
import com.ws.universal.tools.eventbus.BusCode;
import com.ws.universal.tools.eventbus.EventBusUtil;
import com.ws.universal.tools.permission.AppActivityTarget;
import com.ws.universal.tools.permission.PermissionListener;
import com.ws.universal.tools.permission.SettingExecutor;
import com.ws.universal.tools.utils.AppUtils;
import com.ws.universal.tools.utils.CacheUtils;
import com.ws.universal.tools.utils.GsonUtils;
import com.ws.universal.tools.utils.LogcatUtils;
import com.ws.universal.tools.utils.PermissionUtils;
import com.ws.universal.tools.utils.StringUtils;
import com.ws.universal.tools.utils.ToastUtils;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;

public class IndexFragment extends BaseFragment implements NetWorkListener, PermissionListener, OnMapReadyCallback {
    private FragmentIndexBinding binding;

    private GoogleMap mGoogleMap;
    private float zoom = 16F;
    private NearbyNearbyMerchantBean nearbyNearbyMerchantBean;
    private Integer currIndex = -1;
    private Integer indexClickPostion;
    private List<Marker> markers = new ArrayList<>();
    private SellerInfoBean sellerInfoBean;
    //轮询
    private Timer timer;
    private BaseBusData baseBusData;

    @Override
    public View getRootView(LayoutInflater inflater, ViewGroup container) {
        binding = FragmentIndexBinding.inflate(inflater, container, false);
        return binding.getRoot();
    }

    @Override
    public void initView() {
        PermissionUtils.getInstance().CheckPermissions(this, 1002, PermissionUtils.Permission_Location);
        /*找到附近商户*/
        binding.llNearbySeller.setOnClickListener(view -> {
           /* if (PermissionUtils.getInstance().isLocServiceEnable(getContext())) {
                PermissionUtils.getInstance().CheckPermissions(this, 1001, PermissionUtils.Permission_Location);
            } else {
                ToastUtils.showShort(getText(R.string.openSystemLocationService));
            }*/
            if (CacheUtils.getBoolean(Constants.isLogin)) {
               /* if (getLocation() != null) {
                    pageJump(SearchActivity.class);
                } else {
                    ToastUtils.showShort("Location null");
                }*/

                if (PermissionUtils.getInstance().isLocServiceEnable(getContext())) {
                    PermissionUtils.getInstance().CheckPermissions(this, 1001, PermissionUtils.Permission_Location);
                } else {
                    ToastUtils.showShort(getText(R.string.openSystemLocationService));
                }

            } else {
                pageJump(LoginActivity.class);
            }


        });
        //回到原点
        binding.imgLocation.setOnClickListener(view -> {
            PermissionUtils.getInstance().CheckPermissions(this, 1003, PermissionUtils.Permission_Location);

        });


        binding.llLeaseing.setOnClickListener(view -> {
            Bundle bundle = new Bundle();
            bundle.putInt("status", 1);
            bundle.putString("order_no", CacheUtils.getString(Constants.order_no));
            pageJump(MyOrderInfoActivity.class, bundle);
        });

        binding.llShowMerchant.setOnClickListener(view -> {
            Bundle bundle = new Bundle();
            bundle.putString("id", nearbyNearbyMerchantBean.getList().get(indexClickPostion).getId());
            pageJump(NearbySellerInfoActivity.class, bundle);
        });


        if (CacheUtils.getBoolean(Constants.isIease) && CacheUtils.getBoolean(Constants.isLogin)) {

            startPolling(CacheUtils.getString(Constants.order_no));
        }

        uploadApp();
    }

    @Override
    public void autoData() {

    }


    private void uploadApp() {
        Map<String, String> params = new HashMap<>();
        params.put("client", "android");
        //okHttpModel.post(ApiUrl.version_Api, params, ApiUrl.version_Api_ID, this);

    }

    private void initGoogleMap() {
        SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
    }

    @Override
    public void onMapReady(@NonNull GoogleMap googleMap) {
        mGoogleMap = googleMap;
        mGoogleMap.clear();
        if (PermissionUtils.getInstance().isLocServiceEnable(getContext())) {
            if (getLocation() != null) {
                mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(mGoogleMap.getCameraPosition().target, zoom));
                LatLng latLng = new LatLng(getLocation().getLatitude(), getLocation().getLongitude());
                mGoogleMap.addMarker(new MarkerOptions().position(latLng).draggable(true).icon(BitmapDescriptorFactory.fromResource(R.mipmap.icon_my_position)).title("your location"));
                mGoogleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
            }
        } else {
            ToastUtils.showShort(getText(R.string.openSystemLocationService));
        }

        mGoogleMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(@NonNull Marker marker) {
                if (marker.getTag() != null) {
                    LogcatUtils.e(" getTitle " + marker.getTitle());
                    indexClickPostion = Integer.parseInt(marker.getTitle());
                    updateDataIcon();
                    currIndex = indexClickPostion;
                }
                return true;
            }
        });


        mGoogleMap.setOnCameraIdleListener(new GoogleMap.OnCameraIdleListener() {
            @Override
            public void onCameraIdle() {
                for (int i = 0; i < markers.size(); i++) {
                    markers.get(i).setIcon(BitmapDescriptorFactory.fromResource(R.mipmap.icon_merchant));
                    nearbyNearbyMerchantBean.getList().get(i).setChoose(false);
                }
                if (binding.llShowMerchant.getVisibility() == View.VISIBLE) {
                    binding.llShowMerchant.setVisibility(View.GONE);
                }

                LatLng center1 = mGoogleMap.getCameraPosition().target;
                loadData(center1.longitude, center1.latitude);
                baseBusData = new BaseBusData(BusCode.hindMainView);
                EventBusUtil.postEvent(baseBusData);
            }
        });
    }

    private void updateDataIcon() {

        if (currIndex == indexClickPostion) {

            if (nearbyNearbyMerchantBean.getList().get(indexClickPostion).isChoose()) {
                markers.get(indexClickPostion).setIcon(BitmapDescriptorFactory.fromResource(R.mipmap.icon_merchant));
                /*if (binding.llShowMerchant.getVisibility() == View.VISIBLE)
                    binding.llShowMerchant.setVisibility(View.GONE);*/
                baseBusData = new BaseBusData(BusCode.hindMainView);
                EventBusUtil.postEvent(baseBusData);

                nearbyNearbyMerchantBean.getList().get(indexClickPostion).setChoose(false);
            } else {
                markers.get(indexClickPostion).setIcon(BitmapDescriptorFactory.fromResource(R.mipmap.icon_merchanted));
                /*if (binding.llShowMerchant.getVisibility() == View.GONE) {
                    binding.llShowMerchant.setVisibility(View.VISIBLE);
                }*/


                nearbyNearbyMerchantBean.getList().get(indexClickPostion).setChoose(true);

                loadInfo(nearbyNearbyMerchantBean.getList().get(indexClickPostion).getId());
            }

        } else {
            if (currIndex != -1) {

                markers.get(currIndex).setIcon(BitmapDescriptorFactory.fromResource(R.mipmap.icon_merchant));
            }
            markers.get(indexClickPostion).setIcon(BitmapDescriptorFactory.fromResource(R.mipmap.icon_merchanted));

            /*if (binding.llShowMerchant.getVisibility() == View.GONE) {
                binding.llShowMerchant.setVisibility(View.VISIBLE);

            }*/


            for (int i = 0; i < nearbyNearbyMerchantBean.getList().size(); i++) {
                if (i == indexClickPostion) {
                    nearbyNearbyMerchantBean.getList().get(i).setChoose(true);
                } else {
                    nearbyNearbyMerchantBean.getList().get(i).setChoose(false);
                }
            }
            loadInfo(nearbyNearbyMerchantBean.getList().get(indexClickPostion).getId());
        }


    }

    private void refreshMap() {


        if (mGoogleMap != null && getLocation() != null) {
            mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(mGoogleMap.getCameraPosition().target, zoom));
            LatLng latLng = new LatLng(getLocation().getLatitude(), getLocation().getLongitude());
            mGoogleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
        }

    }


    private void removeAllMarkers() {

        for (Marker mLocationMarker : markers) {
            mLocationMarker.remove();
        }
        markers.clear();

    }

    private void stopPolling() {
        if (timer != null) {
            timer.cancel();
            timer.purge();
            timer = null;
        }
    }


    public void startPolling(String order_no) {
        binding.llLeaseing.setVisibility(View.VISIBLE);
        if (timer == null) {
            timer = new Timer();
        }
        timer.schedule(new CommitTimer() {
            @Override
            public void run() {
                selectOrderStatus(order_no);
            }
        }, 0, 3 * 1000);////Teask，延时时间，轮询间隔
    }


    private void loadData(Double longitude, Double latitude) {
        Map<String, String> params = new HashMap<>();
        params.put("longitude", StringUtils.getString(longitude));
        params.put("latitude", StringUtils.getString(latitude));
        params.put("device_type", "powerbank");
        params.put("type", "0");
        okHttpModel.post(ApiUrl.sellerList_Api, params, ApiUrl.sellerList_Api_ID, this);

    }

    private void loadInfo(String id) {
        if (getLocation() != null) {
            showProgressDialog(getContext(), false);
            Map<String, String> params = new HashMap<>();
            params.put("id", id);
            params.put("latitude", StringUtils.getString(getLocation().getLatitude()));
            params.put("longitude", StringUtils.getString(getLocation().getLongitude()));
            params.put("device_type", "powerbank");
            okHttpModel.post(ApiUrl.sellerInfo_Api, params, ApiUrl.sellerInfo_Api_ID, this);
        }
    }

    private void selectOrderStatus(String order_no) {

        Map<String, String> params = new HashMap<>();
        params.put("order_no", order_no);
       // okHttpModel.post(ApiUrl.getStatus_Api, params, ApiUrl.getStatus_Api_ID, this);
    }


    /*** App更新 */
    private void upDateApp(String apkUrl, String content, boolean isCompulsory) {
        PubDiaUtils.getInstance().showOneBtnDialog(getActivity(), getString(R.string.new_version_discovered), content, getString(R.string.update_now), isCompulsory, new PubDiaUtils.PublicDiaologCallback() {
            @Override
            public void onConfirm() {
                Uri uri = Uri.parse(apkUrl);
                Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                startActivity(intent);

            }

            @Override
            public void onCancel() {

            }
        });
    }

    @Override
    public void onSucceed(JSONObject jsonData, int id, CommonalityModel commonality) {
        stopProgressDialog();
        JSONObject data = jsonData.optJSONObject("data");

        switch (id) {
          /*  case ApiUrl.getStatus_Api_ID:
                binding.llLeaseing.setVisibility(View.VISIBLE);

                break;*/
            case ApiUrl.version_Api_ID:
                if (AppUtils.getAppVersionCode() < data.optInt("version")) {
                    if (data.optInt("update") == 1) {
                        upDateApp(data.optString("url"), "", true);
                    } else {
                        upDateApp(data.optString("url"), "", false);
                    }
                }

                break;
            case ApiUrl.sellerList_Api_ID:
                nearbyNearbyMerchantBean = GsonUtils.parseJObject(data.toString(), NearbyNearbyMerchantBean.class);
                if (nearbyNearbyMerchantBean != null) {
                    removeAllMarkers();
                    try {
                        for (int i = 0; i < nearbyNearbyMerchantBean.getList().size(); i++) {
                            Marker marker = mGoogleMap.addMarker(new MarkerOptions().position(new LatLng(nearbyNearbyMerchantBean.getList().get(i).getLatitude(),nearbyNearbyMerchantBean.getList().get(i).getLongitude())).title("" + i)
                                    //.snippet("Population: 4,137,400")
                                    .flat(true).icon(BitmapDescriptorFactory.fromResource(R.mipmap.icon_merchant)));
                            marker.setTag(i);
                            markers.add(marker);
                        }

                    } catch (NullPointerException exception) {

                    }


                }
                break;
            case ApiUrl.sellerInfo_Api_ID:

                sellerInfoBean = GsonUtils.parseJObject(data.toString(), SellerInfoBean.class);
                if (sellerInfoBean != null) {

                    BaseBusData baseBusData = new BaseBusData(BusCode.showMainSellerInfo, sellerInfoBean);
                    EventBusUtil.postEvent(baseBusData);

                   /* binding.tvSellerName.setText(sellerInfoBean.getName());
                    binding.tvSellerAddress.setText(sellerInfoBean.getAddress());
                    binding.tvSellerTime.setText(StringUtils.getString(sellerInfoBean.getShop_start(), "-", sellerInfoBean.getShop_end()));
                    binding.tvItemHire.setText(StringUtils.getString(sellerInfoBean.getBorrow_num()));
                    binding.tvItemReturn.setText(StringUtils.getString(sellerInfoBean.getReturn_num()));
                    binding.tvSellerDstance.setText(StringUtils.getString(sellerInfoBean.getDistance()));

                    GlideUtils.CreateImageRound(sellerInfoBean.getSeller_file(), binding.imgSeller,
                            R.mipmap.icon_defult_nearbylist, R.mipmap.icon_defult_nearbylist);*/

                }

                break;


        }
    }

    @Override
    public void onFail(JSONObject jsonData, int id, CommonalityModel commonality) {
        stopProgressDialog();
        ToastUtils.showShort(commonality.getMessage());
        switch (id) {
            /*case ApiUrl.getStatus_Api_ID:
                binding.llLeaseing.setVisibility(View.GONE);
                CacheUtils.setBoolean(Constants.isIease, false);
                BaseBusData busData = new BaseBusData(BusCode.finishOrder);
                EventBusUtil.postEvent(busData);
                stopPolling();
                break;*/
        }
    }

    @Override
    public void onError(int id, Exception e) {
        stopProgressDialog();
        ToastUtils.showShort(e.getMessage());
    }

    @Override
    public void onPermissionSucceed(int requestCode, @NonNull List<String> grantPermissions) {

        if (requestCode == 1001) {
            pageJump(NearbySellerActivity.class);
        } else if (requestCode == 1002) {
            initGoogleMap();
            if (getLocation() != null)
                loadData(getLocation().getLongitude(), getLocation().getLatitude());
        } else if (requestCode == 1003) {
            refreshMap();
        }
    }

    @Override
    public void onPermissionFailed(int requestCode, @NonNull List<String> deniedPermissions) {
        PubDiaUtils.getInstance().showTwoBtnDialog(getContext(), getString(R.string.permission_hit), getString(R.string.permission_content), getString(R.string.cancel), getString(R.string.sure), new PubDiaUtils.PublicDiaologCallback() {
            @Override
            public void onConfirm() {
                if (mSettingService == null) {
                    mSettingService = new SettingExecutor(new AppActivityTarget(getActivity()), 300);
                }
                mSettingService.execute();
            }

            @Override
            public void onCancel() {

            }
        });
    }


}
